const express = require('express');
const router = express.Router();
const { pool } = require('../database');

// 获取所有科室列表
router.get('/', async (req, res) => {
  try {
    const { hospital_id } = req.query;
    
    let sql = `
      SELECT d.id, d.hospital_id, d.name, d.short_name, d.logo, d.description, 
             d.weight, d.is_available, d.created_at, d.updated_at,
             h.name as hospital_name
      FROM departments d
      LEFT JOIN hospitals h ON d.hospital_id = h.id
    `;
    
    const params = [];
    if (hospital_id) {
      sql += ' WHERE d.hospital_id = ?';
      params.push(hospital_id);
    }
    
    sql += ' ORDER BY d.weight DESC, d.created_at DESC';
    
    const [rows] = await pool.execute(sql, params);
    
    res.json({
      success: true,
      data: rows,
      message: '获取科室列表成功'
    });
  } catch (error) {
    console.error('获取科室列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取科室列表失败',
      error: error.message
    });
  }
});

// 根据ID获取科室详情
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const [rows] = await pool.execute(`
      SELECT d.id, d.hospital_id, d.name, d.short_name, d.logo, d.description, 
             d.weight, d.is_available, d.created_at, d.updated_at,
             h.name as hospital_name
      FROM departments d
      LEFT JOIN hospitals h ON d.hospital_id = h.id
      WHERE d.id = ?
    `, [id]);
    
    if (rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '科室不存在'
      });
    }
    
    res.json({
      success: true,
      data: rows[0],
      message: '获取科室详情成功'
    });
  } catch (error) {
    console.error('获取科室详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取科室详情失败',
      error: error.message
    });
  }
});

// 创建新科室
router.post('/', async (req, res) => {
  try {
    const {
      hospital_id, name, short_name, logo, description, weight, is_available
    } = req.body;
    
    // 验证必填字段
    if (!hospital_id || !name || !short_name) {
      return res.status(400).json({
        success: false,
        message: '医院ID、科室名称和内部简称为必填项'
      });
    }
    
    // 验证医院是否存在
    const [hospital] = await pool.execute('SELECT id FROM hospitals WHERE id = ?', [hospital_id]);
    if (hospital.length === 0) {
      return res.status(400).json({
        success: false,
        message: '指定的医院不存在'
      });
    }
    
    const [result] = await pool.execute(`
      INSERT INTO departments (hospital_id, name, short_name, logo, description, weight, is_available)
      VALUES (?, ?, ?, ?, ?, ?, ?)
    `, [
      hospital_id, name, short_name, logo || null, description || null, 
      weight || 0, is_available !== false
    ]);
    
    res.status(201).json({
      success: true,
      data: { id: result.insertId },
      message: '创建科室成功'
    });
  } catch (error) {
    console.error('创建科室失败:', error);
    res.status(500).json({
      success: false,
      message: '创建科室失败',
      error: error.message
    });
  }
});

// 更新科室信息
router.put('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const {
      hospital_id, name, logo, description, weight, is_available
    } = req.body;
    
    // 检查科室是否存在
    const [existing] = await pool.execute('SELECT id FROM departments WHERE id = ?', [id]);
    if (existing.length === 0) {
      return res.status(404).json({
        success: false,
        message: '科室不存在'
      });
    }
    
    // 如果更新了医院ID，验证新医院是否存在
    if (hospital_id) {
      const [hospital] = await pool.execute('SELECT id FROM hospitals WHERE id = ?', [hospital_id]);
      if (hospital.length === 0) {
        return res.status(400).json({
          success: false,
          message: '指定的医院不存在'
        });
      }
    }
    
    await pool.execute(`
      UPDATE departments SET
        hospital_id = ?, name = ?, logo = ?, description = ?, 
        weight = ?, is_available = ?, updated_at = CURRENT_TIMESTAMP
      WHERE id = ?
    `, [
      hospital_id, name, logo, description, weight, is_available, id
    ]);
    
    res.json({
      success: true,
      message: '更新科室信息成功'
    });
  } catch (error) {
    console.error('更新科室信息失败:', error);
    res.status(500).json({
      success: false,
      message: '更新科室信息失败',
      error: error.message
    });
  }
});

// 删除科室
router.delete('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    // 检查科室是否存在
    const [existing] = await pool.execute('SELECT id FROM departments WHERE id = ?', [id]);
    if (existing.length === 0) {
      return res.status(404).json({
        success: false,
        message: '科室不存在'
      });
    }
    
    // 删除科室（会级联删除相关数据）
    await pool.execute('DELETE FROM departments WHERE id = ?', [id]);
    
    res.json({
      success: true,
      message: '删除科室成功'
    });
  } catch (error) {
    console.error('删除科室失败:', error);
    res.status(500).json({
      success: false,
      message: '删除科室失败',
      error: error.message
    });
  }
});

// 更新科室状态
router.patch('/:id/status', async (req, res) => {
  try {
    const { id } = req.params;
    const { is_available } = req.body;
    
    if (typeof is_available !== 'boolean') {
      return res.status(400).json({
        success: false,
        message: 'is_available 必须为布尔值'
      });
    }
    
    await pool.execute(
      'UPDATE departments SET is_available = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
      [is_available, id]
    );
    
    res.json({
      success: true,
      message: `科室已${is_available ? '启用' : '禁用'}`
    });
  } catch (error) {
    console.error('更新科室状态失败:', error);
    res.status(500).json({
      success: false,
      message: '更新科室状态失败',
      error: error.message
    });
  }
});

// 更新科室权重
router.patch('/:id/weight', async (req, res) => {
  try {
    const { id } = req.params;
    const { weight } = req.body;
    
    if (typeof weight !== 'number') {
      return res.status(400).json({
        success: false,
        message: 'weight 必须为数字'
      });
    }
    
    await pool.execute(
      'UPDATE departments SET weight = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
      [weight, id]
    );
    
    res.json({
      success: true,
      message: '更新科室权重成功'
    });
  } catch (error) {
    console.error('更新科室权重失败:', error);
    res.status(500).json({
      success: false,
      message: '更新科室权重失败',
      error: error.message
    });
  }
});

module.exports = router;
